import { ref, computed } from 'vue';
import { asset } from '@/server/asset';
import { stock_list } from '@/service/market';
import { toast } from '@/service/status';

// 投资组合总市值
export const totle_value = computed(() => {
    let value = 0;
    for (let i = 0; i < holding_list.value.length; i++) {
        let item = holding_list.value[i];
        let shares = item.shares;
        for (let i = 0; i < stock_list.value.length; i++) {
            if (item.symbol == stock_list.value[i].shortName) {
                value += shares * parseFloat(stock_list.value[i].price.slice(1));
                break;
            }
        }
    }
    return value;
});
// 今日变更组合总市值
export const change_value = computed(() => {
    let value = 0;
    for (let i = 0; i < holding_list.value.length; i++) {
        let item = holding_list.value[i];
        let old_price = item.avgPrice;
        let new_price = 0;
        for (let i = 0; i < stock_list.value.length; i++) {
            if (item.symbol == stock_list.value[i].shortName) {
                new_price = stock_list.value[i].price;
                new_price = parseFloat(new_price.slice(1));
                break;
            }
        }
        // 避免没开市算出一个极大的负数影响用户体验
        if (new_price == 0) continue;
        value += (new_price - old_price) * item.shares;
    }
    return value;
});
// 投资组合总市值涨跌幅
export const change_rate = computed(() => {
    if (totle_value.value == 0) return '+0.00';
    // let change_rate_value = (change_value.value / totle_value.value * 100).toFixed(2);
    let change_rate_value = (change_value.value / (totle_value.value - change_value.value) * 100).toFixed(2);
    return change_rate_value >= 0 ? `+${ change_rate_value }` : change_rate_value;
});

// 当前用户持有的 美股 列表
export const holding_list = ref([
    // {
    //     id: item.id,
    //     symbol: item.shortName,
    //     name: item.fullName,
    //     shares: item.quantity,
    //     price: item.avgPrice,
    //     limitQuantity: item.limitQuantity,
    //     marketSymbol: item.marketSymbol,
    //     avgPrice: item.avgPrice,
    //     marketCap: item.marketCap,
    //     orderSide: item.orderSide,
    //     status: item.status,
    //     openTime: item.openTime,
    // },
]);

export const open_list = ref([]);
export const close_list = ref([]);

export const assetService = {
    async getStockOrderList() {
        let res = await asset.getStockOrderList();
        if (res.success) {
            if (res.data.code == 200) {
                let list = res.data.data;
                let new_list = [];
                for (let i = 0; i < list.length; i++) {
                    let item = list[i];
                    let obj = {
                        id: item.id,
                        symbol: item.shortName,
                        name: item.fullName,
                        shares: item.quantity,
                        price: item.avgPrice,
                        limitQuantity: item.limitQuantity,
                        marketSymbol: item.marketSymbol,
                        avgPrice: item.avgPrice,
                        marketCap: item.marketCap,
                        orderSide: item.orderSide,
                        status: item.status,
                        openTime: item.openTime,
                    };
                    new_list.push(obj);
                }
                holding_list.value = new_list;
            } else {
                // toast.warning('Holding Failed! Please try again later!');
            }
        } else {
            // if (res.err.message == 'token is null') {
            //     toast.warning('Holding Failed! Please try again after login!', 2000);
            // } else {
            //     toast.warning('Holding Failed! Please try again later!');
            // }
        }
    },
    // 获取开仓记录接口
    async getStockOpenList() {
        let res = await asset.getStockOpenList();
        if (res.success) {
            if (res.data.code == 200) {
                let list = res.data.data.list;
                let new_list = [];
                for (let i = 0; i < list.length; i++) {
                    let item = list[i];
                    let obj = {
                        id: item.id,
                        fullName: item.fullName,
                        shortName: item.shortName,
                        openType: item.openType,
                        openSide: item.openSide,
                        quantity: item.quantity,
                        openPrice: item.openPrice,
                        marketCap: item.marketCap,
                        feeRate: item.feeRate,
                        fee: item.fee,
                        totalAmount: item.totalAmount,
                        openTime: item.openTime,
                        createTime: item.createTime,
                        status: item.status,
                    };
                    new_list.push(obj);
                }
                open_list.value = new_list;
                console.log('获取成功', res, new_list, open_list);
            } else {
                // if (res.err.message == 'token is null') {
                //     toast.warning('Trading Record Failed! Please try again after login!', 2000);
                // } else {
                //     toast.warning('Trading Record Failed! Please try again later!');
                // }
            }
        } else {
            // if (res.err.message == 'token is null') {
            //     toast.warning('Trading Record Failed! Please try again after login!', 2000);
            // } else {
            //     toast.warning('Trading Record Failed! Please try again later!');
            // }
        }
    },
    // 获取平仓记录接口
    async getStockCloseList() {
        let res = await asset.getStockCloseList();
        if (res.success) {
            if (res.data.code == 200) {
                let list = res.data.data.list;
                let new_list = [];
                for (let i = 0; i < list.length; i++) {
                    let item = list[i];
                    let obj = {
                        id: item.id,
                        fullName: item.fullName,
                        shortName: item.shortName,
                        quantity: item.quantity,
                        closeSide: item.closeSide,
                        closeType: item.closeType,
                        marketCap: item.marketCap,
                        avgPrice: item.avgPrice,
                        feeRate: item.feeRate,
                        fee: item.fee,
                        closePrice: item.closePrice,
                        profit: item.profit,
                        closeTime: item.closeTime,
                        createTime: item.createTime,
                        status: item.status,
                    };
                    new_list.push(obj);
                }
                close_list.value = new_list;
            } else {
                // if (res.err.message == 'token is null') {
                //     toast.warning('Trading Record Failed! Please try again after login!', 2000);
                // } else {
                //     toast.warning('Trading Record Failed! Please try again later!');
                // }
            }
        } else {
            // if (res.err.message == 'token is null') {
            //     toast.warning('Trading Record Failed! Please try again after login!', 2000);
            // } else {
            //     toast.warning('Trading Record Failed! Please try again later!');
            // }
        }
    },
};

// 是否弹出平仓或者加仓的窗口
export const show_close_stock = ref(false);

// 弹出平仓窗口
export function openStockCloseModel(item) {
    Object.assign(stock_close_order.value, item);
    console.log('打开平仓窗口', stock_close_order, item);
    show_close_stock.value = true;
}

// 关闭平仓窗口
export function closeStockCloseModel() {
    show_close_stock.value = false;
}

// 平仓订单数据
export const stock_close_order = ref({
    id: "",
    symbol: "",
    name: "",
    shares: "",
    price: "",
    limitQuantity: "",
    marketSymbol: "",
    avgPrice: "",
    marketCap: "",
    orderSide: "",
    status: "",
    openTime: "",
});